﻿namespace hedefgrup.reports.renault.verbatim
{
    using hedefgrup.reports.renault.calculators;
    using hedefgrup.reports.renault.database;
    using hedefgrup.reports.renault.date;
    using hedefgrup.reports.renault.definitions;
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.Web;
    using System.Collections.Specialized;

    public class verbatimReportInfo
    {
        private int answerCount;
        private string content;
        private int rowIndex;

        private verbatimReportInfo(int rowIndex, string content, int answerCount)
        {
            this.rowIndex = rowIndex;
            this.answerCount = answerCount;
            this.content = content;
        }

        internal static verbatimReportInfo fromDataRow(int rowIndex, DataRow row)
        {
            return new verbatimReportInfo(rowIndex, Convert.ToString(row["Content"]), Convert.ToInt32(row["AnswerCount"]));
        }

        public static NameValueCollection getVaryByDistinctValuesAndTexts(string projectCode, string makeSelection, string questionCode)
        {
            questionDefinition question = dataCache.getDataCacheByProjectName(projectCode, makeSelection).questionDefinitions[questionCode];
            SortedList<int, optionDefinition> options = question.optionDefinitions;

            NameValueCollection distinctValues = new NameValueCollection();
            distinctValues.Add("", question.getName() + " - Tümü");
            foreach (optionDefinition option in options.Values)
            {
                distinctValues.Add(option.getValue().ToString(), option.getText());
            }

            return distinctValues;
        }

        public static verbatimReportInfo[] select(string projectCode, string makeSelection, string filter, string questionCode, reportMonth month, int cumulativeMonths, dealerDefinition dealer, int startIndex, int count, string varyByColumn, string varyByFilter)
        {
            string str = "SELECT V.[Content], COUNT(*) as AnswerCount FROM renault_verbatim V [[[VARYBYJOIN]]] WHERE V.[CARPAN] <= @p_0 AND V.[CARPAN] >= @p_1 AND V.[Question] = @p_2 AND V.[Project] = @p_3 [[[BAYII]]] [[[MARKA]]] [[[VARYBYFILTER]]] GROUP BY [Content]";

            string dataTableName = dataCache.getDataCacheByProjectName(projectCode, makeSelection).dataTableName;

            List<object> argsList = new List<object>(new object[] { month.getMonthYearValue(), (month - (cumulativeMonths - 1)).getMonthYearValue(), questionCode, projectCode });
            if (!string.IsNullOrEmpty(varyByColumn))
            {
                argsList.Add(varyByFilter);
            }
            object[] args = argsList.ToArray();

            reportCalculator calculator = null;
            if (HttpContext.Current.Handler is reportPage)
            {
                calculator = (HttpContext.Current.Handler as reportPage).getCalculator();
            }
            else
            {
                calculator = reportCalculator.getReportCalculatorByProjectName(projectCode, makeSelection);
            }
            string newValue = "";
            if (dealer != calculator.getRelatedDataCache().getRootDealer())
            {
                newValue = " AND V.[BAYII] IN ('" + dealer.getCode().TrimStart(new char[] { '0' }) + "',";
                dealerDefinition[] definitionArray = calculator.getNonVirtualChildren(dealer);
                if (dealer.getTypeCode() == "connectedPoints_total")
                {
                    definitionArray = dealer.children.ToArray();
                }
                foreach (dealerDefinition definition in definitionArray)
                {
                    newValue = newValue + "'" + definition.getCode().TrimStart(new char[] { '0' }) + "',";
                }
                newValue = newValue.Substring(0, newValue.Length - 1) + ")";
            }

            string finalSelectStatement = str
                .Replace("[[[VARYBYJOIN]]]", string.IsNullOrEmpty(varyByColumn) ? "" : " JOIN " + dataTableName + " D ON D.IID = V.IID AND V.CARPAN = D.YIL * 12 + D.AY")
                .Replace("[[[BAYII]]]", newValue)
                .Replace("[[[MARKA]]]", " AND " + filter.Replace("MARKA", "V.MARKA"))
                .Replace("[[[VARYBYFILTER]]]", string.IsNullOrEmpty(varyByColumn) ? "" : "AND CHARINDEX(@p_4, D." + varyByColumn + ") > 0");

            DataTable table = db.query(finalSelectStatement, args);
            List<verbatimReportInfo> list = new List<verbatimReportInfo>(table.Rows.Count);
            int num = 1;
            foreach (DataRow row in table.Rows)
            {
                list.Add(fromDataRow(num++, row));
            }
            return list.ToArray();
        }

        public int AnswerCount
        {
            get
            {
                return this.answerCount;
            }
        }

        public string Content
        {
            get
            {
                return this.content;
            }
        }

        public int RowIndex
        {
            get
            {
                return this.rowIndex;
            }
        }
    }
}

